<?php
$activity_id = $_GET['activity_id']??0;
require_once '../../api/swooleChat/ChatManager.php';
$manage = new ChatManager();
$room_id = 'activity_' . $activity_id;
$sum_watch_num=$manage->getRoomSumPeople($room_id);
$watch_num=$manage->getRoomNowPeople($room_id);
$banned_user_list=$manage->getBannedUser($room_id);
function getUsername($user_id){
    return getOneRowDataFromDatabase('user_co', 'username', "id={$user_id}")['data']['username'] ?? '';
}
?>
<!doctype html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>聊天室</title>
    <link href="../css/admin_style.css" type="text/css" rel="stylesheet"/>
    <!-- ZUI 标准版压缩后的 CSS 文件 -->
<!--    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/zui/1.9.1/css/zui.min.css">-->

    <!-- ZUI Javascript 依赖 jQuery -->
<!--    <script src="//cdnjs.cloudflare.com/ajax/libs/zui/1.9.1/lib/jquery/jquery.js"></script>-->
    <!-- ZUI 标准版压缩后的 JavaScript 文件 -->
<!--    <script src="//cdnjs.cloudflare.com/ajax/libs/zui/1.9.1/js/zui.min.js"></script>-->

    <style>
        .content-class{
            max-width: 500px;
            word-break: break-all;
        }
    </style>
</head>
<body>
<table width="100%" border="0" cellpadding="2" cellspacing="1" class="border">
    <tr class="topbg">
        <td colspan="2">管理首页</td>
    </tr>
    <tr class="tdbg">
        <td width="70" height="26" align="right"><strong>管理导航：</strong></td>
        <td><a href="../activity_co/default.php">管理首页</a></td>
    </tr>
</table>

<div style="width: 330px;float: left">
    <div>
        <p>实时在线人数 <input type="text" id="in_watch_num" disabled></p>
        <p>累计观看次数 <input type="text" value="<?php echo $sum_watch_num;?>" disabled></p>
    </div>
    <div style="border: 1px solid #d5ccd2a1">
        <p>房间配置</p>
        <input type="checkbox" value="1" onclick="openChatChange(this)" checked id="open_chat">允许聊天
        <input type="checkbox" value="1" onchange="contentAuditChange(this)" id="need_audit">聊天内容需要审核
    </div>
    <br>
    <div style="border: 1px solid #d5ccd2a1">
        <p>直播状态设置</p>
        <input type="button" onclick="read_connect()" value="连接">
        <input type="button" onclick="disconnect()" value="断开连接">
        <input type="button" onclick="changeLivestatus('live_notstart')" value="直播未开始">
        <input  type="button" onclick="changeLivestatus('living')" value="直播中">
<!--        <input  type="button" onclick="changeLivestatus('living_pause')" value="直播暂停">-->
        <input  type="button" onclick="changeLivestatus('live_stop')" value="直播结束">
    </div>
    <br>
    <div style="border: 1px solid #d5ccd2a1">
        <p>聊天框</p>
        <input type="text" id="msg" style="width: 300px;height: 200px;"/>
        <input type="button" onclick="send_msg(this)" id="bt_send_msg" value="发送消息">
    </div>
    <br>
    <div>
        <div  style="display: none">
            <span>用户id</span>
            <input type="text" id="user_id" placeholder="1" value="0">
        </div>
    <input type="text" id="m_type" value="activity" style="display: none">
    <input type="text" id="m_type_id" value="<?php echo $activity_id?>" style="display: none">


    </div>
    <br>
    <br>

</div>
<div style="float: left;background-color: rgba(222,222,222,0.35);min-width: 600px;max-height: 400px;max-width: 1100px  ;  overflow: auto;" id="msg_list2">
<!--    <table width="100%" border="0" cellpadding="2" cellspacing="1" class="border">-->
    <table class="border" style="max-height: 400px ">

        <thead>
        <tr class="title">
            <th width="100" >来源</th>
            <th width="100" >用户</th>
            <th width="400" >内容</th>
            <th width="100" >状态</th>
            <th width="100" >操作</th>
        </tr>
        </thead>
        <tbody id="msg_list">
        </tbody>
    </table>
    <p class="p">

    </p>
</div>

<div style="float: left;background-color: rgba(222,222,222,0.35);max-height: 400px;max-width: 300px  ;  overflow: auto;" id="jy_list2">
<!--    <table width="100%" border="0" cellpadding="2" cellspacing="1" class="border">-->
    <table class="border" style="max-height: 400px ">

        <thead>
        <tr class="title">
            <th width="100" >禁言列表</th>
            <th width="100" >用户</th>
            <th width="100" >操作</th>
        </tr>
        </thead>
        <tbody id="jy_list">
        <?php
        foreach ($banned_user_list as $item) {
            $usermma=getUsername($item);
            echo "
<tr>
<td></td>
<td>{$usermma}</td>
<td><input type=\"button\" onclick=\"bannedToPost(this,0,{$item})\" value=\"解开禁言\"></td>

</tr>
";
        }
        ?>
        </tbody>
    </table>
    <p class="p">

    </p>
</div>


<script src="../scripts/jquery2.2.2.min.js"></script>
<script>
    var websocket;
    var open_chat=1;//允许聊天
    var need_audit=0;//内容需要审核
    var serve_data;//服务端返回的数据
    var live_status='live_notstart';//直播状态
    var username='阜阜';//官方账号名称
    var img_sl='https://xxxxx.com/admin/live_record_co/img/img.jpg';//头像地址
    var user_level='0';//用户等级
</script>

<script>

    //修改直播状态
    function changeLivestatus(status){
        let data2=sendChatMsg('config');
        let mm=JSON.parse(data2);
        mm.live_status = status;
        let data=JSON.stringify(mm);
        websocket.send(data);
        live_status=status
        alert('操作成功');
    }
    function stop_live(){

    }

    //打开聊天 允许聊天
    function openChatChange(obj){
        if($(obj).is(':checked')){
            console.log('open');
            open_chat=1;
        }else{
            console.log('close');
            open_chat=0;
        }
        let data2=sendChatMsg('config');
        websocket.send(data2);
        updateChatSet(open_chat, need_audit);
        alert('操作成功');
    }
    //内容是否审核
    function contentAuditChange(obj){
        if($(obj).is(':checked')){
            need_audit = 1;
            console.log('open');
        }else{
            need_audit = 0;
            console.log('close');
        }
        let data2=sendChatMsg('config');
        websocket.send(data2);
        updateChatSet(open_chat, need_audit);
        alert('操作成功');
    }

    //修改某条信息的通过或者不通过
    function chatOneConfig(obj,action='pass',msg_record_id){
        // todo 增加用户名 头像 内容  把聊天内容列表修改为表格
        let data2=sendChatMsg('chat_one_pass_status');
        let mm=JSON.parse(data2);
        mm.msg_record_id=msg_record_id;
        // let username=$(obj).parent().parent().parent().prev().prev().text();
        // let content=$(obj).parent().parent().parent().prev().text();
        // console.log(username);
        // mm.username = content.username;
        // mm.content = content.content;
        // mm.user_id = content.content;
        if(action=='pass'){
            mm.pass=1;
        }else if(action=='nopass'){
            mm.pass=0;
        }
        let data=JSON.stringify(mm);
        websocket.send(data);
        alert('操作成功');
    }
    //禁止某个用户发言
    function bannedToPost(obj,banned=0,user_id) {
        let data2=sendChatMsg('chat_user_banned');
        let mm=JSON.parse(data2);
        mm.banned=banned;
        mm.user_id = user_id;
        console.log(mm);
        let data=JSON.stringify(mm);
        console.log(data);
        websocket.send(data);
        alert('操作成功');
    }
    //删除某条发言
    function deleteToPost(obj,msg_recoid=0) {
        let data2=sendChatMsg('chat_one_delete');
        let mm=JSON.parse(data2);
        mm.msg_record_id=msg_recoid;
        let data=JSON.stringify(mm);
        websocket.send(data);
        alert('操作成功');
    }
    //连接
    function read_connect() {
        $("#msg_list").html('');
        let hostss=window.location.host;
        console.log(hostss);
        let wsServer = 'ws://'+hostss+'/socket';
        // let wsServer = 'ws://47.56.192.62:9502';

        try {
            if (websocket.readyState == 1) {
                websocket.close();
            }
            console.log(websocket.readyState);
        }catch (err){

        }
        console.log(wsServer);
        websocket = new WebSocket(wsServer);

        websocket.onopen = function (evt) {
            console.log("Connected to WebSocket server.");
            let data2 = sendChatMsg('join');
            console.log(data2);
            websocket.send(data2);
        };

        websocket.onclose = function (evt) {
            console.log("Disconnected");
        };

        websocket.onmessage = function (evt) {
            console.log('Retrieved data from server: \n' + evt.data);
            serve_data = evt.data;
            try {
                let msg_arr = JSON.parse(evt.data);
                console.log(msg_arr);
                //判断是什么类型
                if (msg_arr.type == 'chat') {
                    let msg;
                    console.log('到这了2');
                    if($("#user_id").val()==0) {
                        console.log('到这了1');
                        msg = getMsgListStyle('serve_send', msg_arr);
                        console.log('fffff');
                        $("#msg_list").append(msg);
                    }else{
                        if(msg_arr.pass==1){
                            msg = getMsgListStyle('serve_send', msg_arr);
                            $("#msg_list").append(msg);
                        }
                    }
                } else if (msg_arr.type == 'new_watch_join') {
                    // $("#in_watch_num").val(msg_arr.watch_num);
                }else if (msg_arr.type == 'join') {
                    //进入房间 初始化以前聊天内容
                    open_chat = msg_arr.open_chat;
                    need_audit = msg_arr.need_audit;
                    live_status = msg_arr.live_status;
                    updateChatSet(msg_arr.open_chat, msg_arr.need_audit);
                    let msg = getMsgListStyle('serve_record_list', msg_arr.chat_room_msg_list);
                    $("#msg_list").append(msg);
                }else if (msg_arr.type == 'config') {
                    //配置
                    open_chat = msg_arr.open_chat;
                    need_audit = msg_arr.need_audit;
                    live_status = msg_arr.live_status;
                    updateChatSet(msg_arr.open_chat, msg_arr.need_audit);
                }else if (msg_arr.type == 'chat_return') {
                    //配置
                    let msg = getMsgListStyle('chat_return', msg_arr);
                    $("#msg_list").append(msg);
                }

                $("#in_watch_num").val(msg_arr.watch_num);
            }catch(err){

            }
            let div = document.getElementById('msg_list2');
            div.scrollTop = div.scrollHeight;
        };

        websocket.onerror = function (evt, e) {
            console.log('Error occured: ' + evt.data);
        };
    }

    //更新配置
    function updateChatSet(open_chat,need_audit) {
        if(open_chat==0){//允许聊天
            $("#open_chat").prop("checked",false);
            $("#bt_send_msg").attr({disabled:'disabled'})
        }else{
            $("#open_chat").prop("checked",true);
            $("#bt_send_msg").removeAttr('disabled')
        }
        if(need_audit==1){//内容需要审核
            // todo 内容需要审核
            $('#need_audit').prop("checked",true);
        }else{
            $('#need_audit').prop("checked",false);

        }
    }

    function disconnect() {
        $("#msg_list").html('');
        websocket.close();
    }
    // 获得聊天列表的样式 typ(my_send 自己发送的,serve_send服务器分发来的) serve_record_list 房间聊天记录
    function getMsgListStyle(type,content=''){
        let dm=$("#msg").val();
        let html=`
`;
        // if(type=='my_send'){
        if(type=='chat_return'){
            let pass_text='<span class="red">未审核</span>';
            if(need_audit==0){
                pass_text=`<span class="green">已审核</span>`
            }
            html+=`
            <tr  class="tdbg">
            <td>服务器推送</td>
            <td>当前客户端</td>
            <td>${dm}</td>
            <td>${pass_text}</td>
            <td>
            <div class="btn-group" data-toggle="buttons">

    <input type="button" onclick="chatOneConfig(this,'pass',${content.msg_record_id})" value="审核通过">


    <input type="button" onclick="chatOneConfig(this,'nopass',${content.msg_record_id})" value="审核不通过">


    <input type="button" onclick="bannedToPost(this,1,${content.user_id})" value="禁言">


    <input type="button" onclick="bannedToPost(this,0,${content.user_id})" value="解开禁言">



    <input type="button" onclick="deleteToPost(this,${content.msg_record_id})" value="删除">


</div>

</td>
</tr>
            `;
        }
        if(type=='serve_send'){
            let pass_text='<span class="red">未审核</span>';
            if(content.pass==1){
                pass_text=`<span class="green">已审核</span>`
            }
            html+=`
            <tr  class="tdbg">
            <td>服务器推送</td>
            <td>${content.username}</td>
            <td>${content.content}</td>
            <td class="content-class">${pass_text}</td>
            <td>
            <div class="btn-group" data-toggle="buttons">

    <input type="button" onclick="chatOneConfig(this,'pass',${content.msg_record_id})" value="审核通过">


    <input type="button" onclick="chatOneConfig(this,'nopass',${content.msg_record_id})" value="审核不通过">


    <input type="button" onclick="bannedToPost(this,1,${content.user_id})" value="禁言">


    <input type="button" onclick="bannedToPost(this,0,${content.user_id})" value="解开禁言">



    <input type="button" onclick="deleteToPost(this,${content.msg_record_id})" value="删除">


</div>
</td>
</tr>
            `;
//                 html += `<div>服务器推送内容[[[
// <p>用户：${content.username}: <span>${content.content}</span></p>
//
// <input type="button" onclick="chatOneConfig(this,'pass')" value="${content.msg_record_id}"/>审核通过
// <input type="button" onclick="chatOneConfig(this,'nopass')" value="${content.msg_record_id}"/>审核不通过
// <input type="button" onclick="bannedToPost(this,1)" value="${content.user_id}"/>禁言
// <input type="button" onclick="bannedToPost(this,0)" value="${content.user_id}"/>解开禁言
// </div>`
            // html = `<p>服务器推送内容：${content}</p>`
        }
        if(type=='serve_record_list'){
            console.log(content);
            for(let i=0;i<content.length;i++){

//                 html += `<div>服务器推送内容[[[
// <p>用户：${content[i].username}: <span>${content[i].content}</span></p>
// <input type="button" onclick="chatOneConfig(this,'pass')" value="${content[i].msg_record_id}"/>通过
// <input type="button" onclick="chatOneConfig(this,'nopass')" value="${content[i].msg_record_id}"/>不通过
// <input type="button" onclick="bannedToPost(this,1)" value="${content[i].user_id}"/>禁言
// <input type="button" onclick="bannedToPost(this,0)" value="${content[i].user_id}"/>解开禁言
// </div>`

                let pass_text='<span class="red">未审核</span>';
                if(content[i].pass==1){
                    pass_text=`<span class="green">已审核</span>`
                }
                // let banned_text = `<span>正常</span>`;
                // if(content[i].banned==1){
                //     banned_text=`<span class="green">禁言中</span>`
                // }
                html+=`
            <tr class="tdbg">
            <td>服务器推送</td>
            <td>${content[i].username}</td>
            <td class="content-class">${content[i].content}</td>
            <td>${pass_text}</td>
            <td>
            <div class="btn-group" data-toggle="buttons">

    <input type="button" onclick="chatOneConfig(this,'pass',${content[i].msg_record_id})" value="审核通过">


    <input type="button" onclick="chatOneConfig(this,'nopass',${content[i].msg_record_id})" value="审核不通过">


    <input type="button" onclick="bannedToPost(this,1,${content[i].user_id})" value="禁言">


    <input type="button" onclick="bannedToPost(this,0,${content[i].user_id})" value="解开禁言">


    <input type="button" onclick="deleteToPost(this,${content[i].msg_record_id})" value="删除">

</div>
</td>
</tr>
            `;
            }
        }
        html += ``;

        return html;
    }

    //发送消息
    function send_msg(obj) {
        let data2 = sendChatMsg('chat');
        let dm=$("#msg").val();
        if(need_audit==1){
            // todo 内容需要审核
        }else{

        }
        let html=getMsgListStyle('my_send');
        $("#msg_list").append(html);
        websocket.send(data2);
        let div = document.getElementById('msg_list2');
        div.scrollTop = div.scrollHeight;
    }

    /**
     * 发送消息
     * @returns {string}
     */
    function sendChatMsg(type='',content) {
        let msg = '';
        let mm=new Object();
        let m_type=$("#m_type").val();
        let m_type_id=$("#m_type_id").val();
        let user_id=$("#user_id").val();
        mm.m_type = m_type;
        mm.m_type_id = m_type_id;
        mm.chat_room_id=m_type+'_'+m_type_id;
        mm.type = type;
        mm.user_id = user_id;
        if(need_audit==1) {
            mm.pass = 0;
        }else{
            mm.pass = 1;
        }

        if(type=='config'){
            mm.open_chat = open_chat;
            mm.need_audit = need_audit;
            mm.live_status = live_status;

        }else if(type=='chat_live_status'){

        }else if(type=='chat_one_pass_status'){
            mm.msg_record_id=0;
            mm.delete=0;
        }else if(type=='chat_user_banned'){
            mm.banned=0;//禁止发言
        }else if(type=='chat_one_delete'){

        }else {
            mm.user_level = user_level;
            mm.username = username;
            mm.img_sl = img_sl;
            mm.content = msg;

            if (type == 'join') {
                mm.type = 'join';
            } else {//chat
                // mm.type = 'chat';
                msg = $("#msg").val();
                mm.content = msg;
            }
        }
        let data2 = JSON.stringify(mm);
        console.log(data2);
        return data2;
    }
    function heartbeat_bag(){

        let m_type=$("#m_type").val();
        let m_type_id=$("#m_type_id").val();
        let chat_room_id=m_type+'_'+m_type_id;

        let mm=new Object();
        let user_id=$("#user_id").val();
        mm.user_level = user_level;
        mm.img_sl = img_sl;
        mm.user_id = user_id;
        mm.chat_room_id = chat_room_id;
        mm.m_type = m_type;
        mm.m_type_id = m_type_id;
        mm.type = 'heartbrat_bag';
        websocket.send(JSON.stringify(mm));
    }

</script>

<script>
    //    进入自动连接
    read_connect();

    //心跳包
    setInterval('heartbeat_bag()',15000)
</script>

<!-- HTTP -->
<!--<script src="http://cdn.ronghub.com/RongIMLib-3.0.0-dev.js"></script>-->
<!-- HTTPS -->
<!--<script src="https://cdn.ronghub.com/RongIMLib-3.0.0-dev.js"></script>-->
<!-- 压缩版 -->
<!--<script src="https://cdn.ronghub.com/RongIMLib-3.0.0-dev.min.js"></script>-->


<!--<script>-->
<!--    var config = {-->
<!--        appkey: 'pgyu6atqpm8vu',-->
<!--    };-->
<!--    var im = RongIMLib.init(config);-->
<!---->
<!--    var token='';-->
<!--//链接服务-->
<!--    $.ajax({-->
<!--        url:'/api/rongyun/getToken.api.php',-->
<!--        data:{-->
<!--            user_id:'1',-->
<!--            name:'管理员',-->
<!--            portrait:'xx'-->
<!--        },-->
<!--        type:'post',-->
<!--        dataType:'json',-->
<!--        async:false,-->
<!--        success:function(res){-->
<!--            token=res.data.token;-->
<!--            console.log(res);-->
<!--        }-->
<!---->
<!--    });-->
<!--    console.log(token);-->
<!--    var user = {-->
<!--        token: '53KsjNRpBG+BByZaMFm1YFYYemqVH5Ha@iq6n.cn.rongnav.com;iq6n.cn.rongcfg.com'-->
<!--    };-->
<!--    // im 来自 RongIMLib.init 返回的实例，例如：var im = RongIMLib.init({ appkey: 'kj29cjn0l1myd' });-->
<!--    im.connect(user).then(function(user) {-->
<!--        console.log('链接成功, 链接用户 id 为: ', user.id);-->
<!--    }).catch(function(error) {-->
<!--        console.log('链接失败: ', error.code, error.msg);-->
<!--    });-->
<!---->
<!---->
<!--    //    监听-->
<!--    var conversationList = []; // 当前已存在的会话列表-->
<!--    im.watch({-->
<!--        conversation: function(event){-->
<!--            var updatedConversationList = event.updatedConversationList; // 更新的会话列表-->
<!--            console.log('更新会话汇总:', updatedConversationList);-->
<!--            console.log('最新会话列表:', im.Conversation.merge({-->
<!--                conversationList,-->
<!--                updatedConversationList-->
<!--            }));-->
<!--        },-->
<!--        message: function(event){-->
<!--            var message = event.message;-->
<!--            console.log('收到新消息:', message);-->
<!--        },-->
<!--        status: function(event){-->
<!--            var status = event.status;-->
<!--            console.log('连接状态码:', status);-->
<!--        }-->
<!--    });-->
<!---->
<!--</script>-->

</body>
</html>